<template>
    <AdminSkeleton>
        <template #header>
            <div class="params">
                <el-form :model="pgform" label-width="auto">
                    <el-form-item label="班组:" size="small">
                        <el-config-provider :value-on-clear="''" :empty-values="['', undefined, null]">
                            <el-select v-model="pgform.persongroup" clearable placeholder="请选择班组" size="small"
                                style="width: 150px" @visible-change="changePg">
                                <el-option v-for="item in useStore.pgs" :label="item.PGNAME" :value="item.PERSONGROUP"
                                    :key="item.PERSONGROUP" />
                            </el-select>
                        </el-config-provider>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" size="small" @click="getLoaction(pgform)"
                            :loading="loading">查询</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </template>
        <template #control>
            <Control :batchIsShow="batchIsShow" :downloadBoxShow="downloadBoxShow" :permObj="permObj"
                @addClick="editLoaction('add', {})" @showDownload="showDownloadBox"
                @downloadExcelPaging="downloadExcelPaging(locations, 'usersTable', '用户信息')"
                @downloadExcelAll="downloadExcelAll(locations, '用户信息')" @batchToggleShow="batchEdit"
                @batchDel="editSubmit('batchDel', selectLocations)" @batchUpload="batchUpload">
            </Control>
        </template>
        <template #content>
            <el-table :data="locations" style="width: 100%" v-loading="loading"
                @selection-change="handleSelectionChange" id="locationsTable">
                <el-table-column type="selection" width="50" v-if="selectShow" />
                <el-table-column prop="LOCATION" label="位置编码" width="100" />
                <el-table-column prop="DESCRIPTION" label="描述" width="120" />
                <el-table-column prop="CUST_LINENUM" label="所属线路" width="120" />
                <el-table-column prop="AREATYPE" label="区域类型" width="80" />
                <el-table-column prop="REMARK" label="备注" width="120" />
                <el-table-column prop="CUST_USETEAM" label="使用班组" width="120" />
                <el-table-column fixed="right" label="Operations" min-width="120" v-perm="permObj.update">
                    <template #default="{ row }">
                        <el-button type="primary" size="small" v-perm="permObj.update"
                            @click="editLoaction('update', row)" title="编辑">
                            <el-icon>
                                <Edit />
                            </el-icon>
                        </el-button>
                        <el-button type="warning" size="small" 
                            @click="editLoaction('copy',row)" title="复制"
                            v-perm="permObj.add"
                        >
                            <el-icon><CopyDocument /></el-icon>
                        </el-button>
                        <el-button type="danger" size="small" class="del" title="删除" v-perm="permObj.delete"
                            @click="editSubmit('delete', row)">
                            <el-icon>
                                <DeleteFilled />
                            </el-icon>
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </template>
    </AdminSkeleton>
    <Drawer ref="drawerRef" :title="title" :size="size" @submit="editSubmit(submitType, editForm)"
        @cancel-submit="resetForm">
        <el-form :model="editForm" ref="updateFormRef" :rules="rules">
            <el-form-item label="位置编码" :label-width="formLabelWidth" prop="LOCATION">
                <el-input v-model="editForm.LOCATION" autocomplete="off" />
            </el-form-item>
            <el-form-item label="描述" :label-width="formLabelWidth" prop="DESCRIPTION">
                <el-input v-model="editForm.DESCRIPTION" autocomplete="off" />
            </el-form-item>
            <el-form-item label="所属线路" :label-width="formLabelWidth" prop="CUST_LINENUM">
                <el-input v-model="editForm.CUST_LINENUM" autocomplete="off" />
            </el-form-item>
            <el-form-item label="区域类型" :label-width="formLabelWidth" prop="AREATYPE">
                <el-input v-model="editForm.AREATYPE" autocomplete="off" />
            </el-form-item>
            <el-form-item label="备注" :label-width="formLabelWidth">
                <el-input v-model="editForm.REMARK" autocomplete="off" />
            </el-form-item>
            <el-form-item label="使用班组" :label-width="formLabelWidth" prop="CUST_USETEAM">
                <el-select v-model="editForm.CUST_USETEAM" placeholder="请选择班组" @visible-change="changePg">
                    <el-option v-for="item in useStore.pgs" :label="item.PGNAME" :value="item.PERSONGROUP" />
                </el-select>
            </el-form-item>
        </el-form>
    </Drawer>
    <Dialog ref="dialogRef" :uploadKeys="uploadKeys" @uploadFile="uploadFile" @closeDialog="closeDialog"
        @batchUpdate="editSubmit('batchUpdate', uploadTable)" @batchAdd="editSubmit('batchAdd', uploadTable)"
        @downloadTemplate="downloadTemplate('upload-table', '位置信息导入模板')">
        <el-table :data="uploadTable" style="width: 100%" ref="dialogTableRef" id="upload-table">
            <el-table-column prop="LOCATION" label="位置编码" width="100" />
            <el-table-column prop="DESCRIPTION" label="描述" width="120" />
            <el-table-column prop="CUST_LINENUM" label="所属线路" width="120" />
            <el-table-column prop="AREATYPE" label="区域类型" width="80" />
            <el-table-column prop="REMARK" label="备注" width="120" />            
            <el-table-column prop="CUST_USETEAM" label="使用班组" width="120"/>            
        </el-table>
    </Dialog>
</template>

<script setup>
import { ref, reactive } from 'vue'
import AdminSkeleton from '@/components/AdminSkeleton.vue'
import Control from '@/components/Control.vue'
import Drawer from '@/components/Drawer.vue'
import Dialog from '@/components/Dialog.vue'
import { getLoactionInfo , editLocation , batchEditLocation} from '@/utils/comminfoApi/area'
import { getPg } from '@/utils/adminApi/usrs'
import { mainStore } from '@/stores/store'
import { msgOpen } from '@/utils/msg'
import { confirm, confirmBatch } from '@/utils/confirm'
import { exportClickFromTableId, exportClickFromDatas } from '@/utils/downloadExcel'
import { objCopy } from '@/utils/objCopy'

//权限对象--用于控制按钮显示
const permObj = {
    add: { name: 'Area', type: 'add' },
    update: { name: 'Area', type: 'update' },
    delete: { name: 'Area', type: 'delete' }
}

//实例化store
const useStore = mainStore()

//弹出层使用
let title = ref("")
let size = ref("35%")
let formLabelWidth = ref("80")

//区域信息查询
//#region 
//查询表单对象
let pgform = reactive({
    persongroup: '',
})

//表格、查询按钮loading状态
let loading = ref(false)

//获取班组信息
const changePg = async () => {
    if (!useStore.pgs.length) {
        let pgs = await getPg()
        useStore.setPgs(pgs.datas.pgs)
    }
}

//区域信息（接收服务器响应后的数据）
let locations = ref([])

/**
 * 获取区域信息
 * @param form  查询参数
 */
const getLoaction = async (form) => {
    // console.log(form)
    loading.value = true
    let res = await getLoactionInfo(form)
    // console.log(res)
    locations.value = res.resDatas.locationInfo
    loading.value = false
}
//#endregion

//批量处理
//#region 
let batchIsShow = ref(false) //展示批量上传、批量删除状态
let selectShow = ref(false) //展示批量勾选状态
let selectLocations = ref([])
let dialogRef = ref(null) //组件ref
let uploadKeys = ref([
    "LOCATION",
    "DESCRIPTION",
    "CUST_LINENUM",
    "AREATYPE",
    "REMARK",
    "CUST_USETEAM",
])

const batchEdit = () => {
    if (locations.value.length) selectShow.value = !selectShow.value
    batchIsShow.value = !batchIsShow.value
}
const handleSelectionChange = (val) => {
    selectLocations.value = val
}

//批量上传
let uploadTable = ref([])
const batchUpload = () => {
    // console.log('batchUpload');
    dialogRef.value.open()
}
//关闭
const closeDialog = () => {
    uploadTable = ref([])
    dialogRef.value.close()
}

//接收子组件传递的excel数据，渲染至界面
let dialogTableRef = ref(null)
const uploadFile = (e) => {
    uploadTable = e.value
}

//下载
let downloadBoxShow = ref(false) //展示下载框状态
const showDownloadBox = () => {
    downloadBoxShow.value = !downloadBoxShow.value
}
/** 
 * 下载当前页
 * @param {Array} data 导出的数据数组对象
 * @param {String} tableId table标签的ID
 * @param {String} fileName 需要命名的文件名
 */
const downloadExcelPaging = (data, tableId, fileName) => {
    data.length ? exportClickFromTableId(tableId, fileName) : msgOpen("无数据可供下载，请先查询数据")
}
/**
 * 下载全部
 * @param {Array} data 导出的数据数组对象(未进行分页)
 * @param {String} fileName 需要命名的文件名
 */
const downloadExcelAll = (data, fileName) => {
    if (data.length) {
        let newData = JSON.parse(JSON.stringify(data)) //深拷贝
        for (let i = 0; i < newData.length; i++) {
            newData[i].PASSWORD = ""
        }
        // console.log(newData);        
        exportClickFromDatas(newData, fileName)
    } else {
        msgOpen("无数据可供下载，请先查询数据")
    }
}

/**
 * 导入模版下载
 * @param tableId table标签的ID
 * @param fileName 需要命名的文件名
 */
const downloadTemplate = (tableId, fileName) => {
    // console.log(tableId)
    exportClickFromTableId(tableId, fileName)
}
//#endregion

//编辑区域信息
//#region 
let drawerRef = ref(null) //组件ref
let oldLocationInfo = reactive({
    LOCATION: '',
    DESCRIPTION: '',
    CUST_LINENUM: '',
    AREATYPE: '',
    REMARK: '',
    CUST_USETEAM: '',
}) //用于存储未修改前用户信息
let editForm = reactive({
    LOCATION: '',
    DESCRIPTION: '',
    CUST_LINENUM: '',
    AREATYPE: '',
    REMARK: '',
    CUST_USETEAM: '',
})
//编辑提交类型
let submitType = ref('')


//表单验证ref
let updateFormRef = ref(null)
//输入框验证规则
let rules = reactive({
    LOCATION: [
        { required: true, message: '请输入位置编码', trigger: 'blur' },
    ],
    DESCRIPTION: [
        { required: true, message: '请输入区域描述', trigger: 'blur' },
    ],
    CUST_LINENUM: [
        { required: true, message: '请输入所属线路', trigger: 'blur' },
    ],
    AREATYPE: [
        { required: true, message: '请输入区域类型', trigger: 'blur' },
    ],
    CUST_USETEAM: [
        { required: true, message: '请输入使用班组', trigger: 'blur' },
    ],
})

//重置表单
const resetForm = () => {
    if (submitType.value === 'update') {
        editForm = objCopy(oldLocationInfo, editForm)
    } else if (submitType.value === 'add') {
        editForm = reactive({
            LOCATION: '',
            DESCRIPTION: '',
            CUST_LINENUM: '',
            AREATYPE: '',
            REMARK: '',
            CUST_USETEAM: '',
        })
    }
}

/**
 * @param {String} type 处理类型
 * @param {Object} row 行对象
 */
const editLoaction = (type, row) => {
    submitType.value = type
    drawerRef.value.open()
    if (type === 'update') {
        title.value = "编辑"
        editForm = row
        oldLocationInfo = objCopy(row, oldLocationInfo) //存储未修改前用户信息 
        // console.log(oldUserInfo);                
    }
    if (type === 'add') {
        title.value = "新增"
        resetForm()
    }
    if(type === 'copy'){
        title.value = "复制"
        editForm = objCopy(row,editForm)
        editForm.LOCATION += "_副本"
    }
    // console.log(row);    
}
//#endregion

/**
 * 编辑提交
 * @param type 操作类型
 * @param data 操作数据
 */
const editSubmit = async (type, data) => {
    // console.log(type, data)
    if(type === 'update' || type === 'add' || type === 'copy'){
        updateFormRef.value.validate(async (valid)=>{
            if(!valid){
                return false
            }else{              
                drawerRef.value.showLoading()
                let newLocation = await editLocation(type,data)
                console.log(newLocation)
                drawerRef.value.hideLoading()
                drawerRef.value.close()
                newLocation.status ? msgOpen(newLocation.msg,'success') : msgOpen(newLocation.msg) 
                getLoaction(pgform)              
            }
        })
    }
    if(type === 'delete'){
        let res = await confirm(data.LOCATION)       
        if(res){
            let newLocation = await editLocation(type,data)
            // console.log(newUser);
            msgOpen(newLocation.msg,'success')
            getLoaction(pgform) 
        }  
    }
    if(type === 'batchUpdate' || type === 'batchAdd'){
        let rowsArr = ref([]) 
        let editBatchStatus = ref(true)
        for(let i = 0;i < data.length;i++){
            // console.log(data[i]);            
            if(!data[i].LOCATION.length){
                msgOpen(`第${i + 1 }行错误，请填写LOCATION值！`)
                editBatchStatus.value = false
                break
            }else{
                rowsArr.value.push(data[i])
            }
        }
        if(editBatchStatus.value){
            let newLocation = await batchEditLocation(type,data)  
            // console.log(newLocation)
            dialogRef.value.close()
            uploadTable = ref([])
            if(!newLocation.status){
                msgOpen(newLocation.msg)
            }else{
                newLocation.resDatas.newLocation.rowsAffected ? msgOpen(`${newLocation.msg},共${newLocation.resDatas.newLocation.rowsAffected}条`,"success") 
                                                            : msgOpen(newLocation.msg)
            }        
            getLoaction(pgform)   
        }
    }
    if(type === 'batchDel'){
        if(!data.length){
            msgOpen('未进行勾选，请勾选！')
        }else{
            let isDel = await confirmBatch(data.length) 
            if(isDel){
                let locArr = []
                data?.forEach(item => {
                    let arr = []
                    arr.push(item.LOCATION) 
                    locArr.push(arr)
                })
                let newLocation = await batchEditLocation(type,locArr) 
                if(!newLocation.status){
                    msgOpen(newLocation.msg)
                }else{
                    newLocation.resDatas.newLocation.rowsAffected ? msgOpen(`${newLocation.msg},共${newLocation.resDatas.newLocation.rowsAffected}条`,"success") 
                                                                : msgOpen(newLocation.msg)
                }        
                getLoaction(pgform) 
            }
        }
    }
}

</script>

<style lang="less" scoped>
.params {
    width: 100%;
    height: 100%;

    .el-form {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: flex-start;

        .el-form-item {
            margin-bottom: 0;
            margin-right: .3125rem;
        }
    }

}

.el-table {
    height: 95%;
}
</style>